import { type SqlValue } from "sql.js";
import { ComputedRef, ref } from "vue";

type TTableData = ComputedRef<{
  toRowsArrayHasHeader: () => Generator<SqlValue[], void, unknown>;
}>;

export function useCopyData2excel() {
  function copy(tableData: TTableData) {
    const lines = [];
    for (const row of tableData.value.toRowsArrayHasHeader()) {
      lines.push(
        row
          .map((cell) => (cell === null ? "" : `"${refixCell(cell)}"`))
          .join("\t")
      );
    }

    const excelData = lines.join("\n");

    navigator.clipboard.writeText(excelData).then(() => {
      Quasar.Notify.create({ message: "copied!", position: "top" });
    });
  }

  return {
    copy,
  };
}

function refixCell(cell: string | number | Uint8Array) {
  return cell?.toString().replace(/"/g, '""');
}

export function downloadAsCSV() {
  function core(
    tableData: TTableData,
    kwargs: {
      file_name: string;
    }
  ) {
    // 将二维数组转换为CSV字符串
    function arrayToCSVContent(tableData: TTableData) {
      const lines = [];
      for (const row of tableData.value.toRowsArrayHasHeader()) {
        lines.push(
          row
            .map((cell) => (cell === null ? "" : `"${refixCell(cell)}"`))
            .join(",")
        );
      }

      return lines.join("\n");
    }

    const filename = kwargs.file_name;
    // 创建隐藏的可下载链接
    const csvContent = arrayToCSVContent(tableData);
    const encodedUri = encodeURI(
      `data:text/csv;charset=utf-8,\uFEFF${csvContent}`
    ); // \uFEFF是BOM，用于指示Excel识别UTF-8编码
    const link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", filename);
    link.style.display = "none";

    // 将链接添加到DOM并触发点击事件来下载文件，然后移除链接
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

  return {
    core,
  };
}
